import { Title } from "./title"
import { Content } from "./content"
import Store from "electron-store"
import { changeProgress } from "../index"
import sleep from "sleep-promise"

export async function keyClime(url:string, key:string) {
    let title = new Title(url, key)
	let win = await title.init(key)
    let res = await title.clime(key)

    return {"windows": win, "res": res}
}

export async function goOn(key:string) {
    return clime(key)
}

export async function clime(key:string) {
    let store = new Store()
    let connect = []
    let mission:any = store.get(key+'_link', [])
    if (mission.length == 0) {
        return "没有可执行任务"
    }
    let def = ""
    let res:any = store.get(key, [])
    let mingong = 6
    let climeErrorTime = (<number>store.get('climeErrorTime', 0))
    for (var i = 0; i < mingong; i++) {
        let temp = new Content(def)
        await temp.init(key)
        connect.push(temp)
    }
    console.log("connect", connect)
    console.log("mission:", mission)
    let all = mission.length
    for (var i = all - 1, j = 0; i >= 0; i--, j++) {
        let now = mission.pop();
        console.log("now",now)
        let temp;
        try {
            temp = await connect[j].setUrl(now).getContent(key)
            console.log("j", connect[j]);
            store.set(key + '_link', mission)
            store.set("climeErrorTime", 0)
        } catch (error) {
            for (var i = 0; i < mingong; i++) {
                connect[i].win.close()
            }
            if (<number>store.get('climeErrorTime') < 3)
                clime(key)
            else {
                console.log("错误次数过多")
                console.log(error)
                return false
            }
            store.set("climeErrorTime", (climeErrorTime + 1))
        }

        if (temp != null) {
            res.push(temp)
            store.set(key, res)
        }
        if (j == mingong-1) j = -1;
        changeProgress('getPhoneProcess', (all - i) / all)
        //await sleep(Math.random() * 3000)
    }

    store.set(key, res)

    return {status: 1, windows: connect}
}